import * as XLSX from "xlsx";

export default function useExcel() {
  /**
   * 下载Excel模板
   * @param {string} sheetName 工作表名称
   * @param {Array} data 数据数组，每个子数组代表一行数据
   * @param {string} filename 文件名，默认为"export.xlsx"
   */
  function downloadExcel(sheetName = "Sheet1", data: any = [[]], filename = "export") {
    const newFilename = filename + ".xlsx";
    // 创建一个工作簿
    const workbook = XLSX.utils.book_new();
    // 创建一个工作表
    const worksheet = XLSX.utils.aoa_to_sheet(data);
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
    // 生成Excel文件
    XLSX.write(workbook, { bookType: "xlsx", type: "binary" });
    // 导出为Blob对象并下载
    const wbout = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
    const blob = new Blob([wbout], { type: "application/octet-stream" });
    // 创建 a标签
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = newFilename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }

  /**
   * 上传 Excel
   * @param {File} file 上传文件
   */
  function uploadExcel(file: File, header: any) {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        const headerKey: any = [];
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: "binary" });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData: any = XLSX.utils.sheet_to_json(worksheet);
        //获取表头
        for (const key in jsonData[0]) {
          headerKey.push(key);
        }
        // 把表头替换成对应的英文字段
        const newItem: any = [];
        jsonData.forEach((item: any) => {
          const obj: any = {};
          headerKey.forEach((item1: any) => {
            const label = header[item1];
            const value = isNumber(item[item1]) ? item[item1] : item[item1].trim();
            obj[label] = value;
          });
          newItem.push(obj);
        });
        resolve(newItem);
      };
      reader.readAsArrayBuffer(file);
    });
  }
  return {
    downloadExcel,
    uploadExcel
  };

  function isNumber(obj: any) {
    const reg = /^[0-9]+.?[0-9]*$/;
    if (reg.test(obj)) {
      return true;
    }
    return false;
  }
}
